from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from tkinter import font as tkfont
from threading import Thread
from mini_tools.cjjtool import *
from mini_tools.myexcel import *
from mini_tools.mytools import *
from mini_tools.uitool import *
from sql import sqlseverDB
from config import *
import concurrent.futures as thddd
import tkinter.messagebox as messagebox
import openpyxl,time,concurrent.futures

class AmazonFra(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        Label(self, text='产品采集功能', fg="black", bg="yellow",font=("微软雅黑", 13)).pack(fill=X,padx=2)
        PHMianBanFrame(self,'菲律宾虾皮').pack(fill=X,padx=2,pady=2)
        DinZhiFrame(self).pack(fill=X,padx=2,pady=2)

class PHTaskFrame(Frame):
    def __init__(self,master,taskinfo):
        Frame.__init__(self,master)
        table_name_dict={'虾皮':'HouTai','波兰':'HouTai_ALG','菲律宾虾皮':'ShopeePHAccount'}
        self.task_id=taskinfo['id']
        self.task_name=taskinfo['tName']
        self.table_name=table_name_dict[taskinfo['pt']]
        self.iszd=taskinfo['iszd']
        self.isMulti=taskinfo['isMulti']
        self.timing=taskinfo['timing']
        self.position=taskinfo['position']
        self.mutilTiming=taskinfo['mutilTiming']
        self.extraParam=taskinfo['extraParam']
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.countStr=StringVar(value='正在获取买家号数量')
        self.cjcountStr=StringVar(value='正在获取采集数量')
        self.statusStr=StringVar(value='正在获取任务状态')
        self.startStr=StringVar(value='正在获取上次开始时间')
        self.endStr=StringVar(value='正在获取上次结束时间')
        self.mj_count=10
        self.createWidgets()
        Thread(target=self.getcount).start()

    def createWidgets(self):
        label_font = tkfont.Font(family="微软雅黑", size=10, weight="bold")
        f1=Frame(self)
        f1.pack(fill=X,padx=2)
        
        f00=Frame(f1)
        f00.pack(fill=X,padx=2)
        Label(f00, text=f'《{self.task_name}》',fg='#6B238E',font=("微软雅黑", 12),anchor="w").pack(side=LEFT, padx=2)

        f01=Frame(f1)
        f01.pack(fill=X,padx=2)
        Label(f01, textvariable=self.countStr,fg='#236B8E').pack(side=LEFT, padx=2)

        f02=Frame(f1)
        f02.pack(fill=X,padx=2)
        Label(f02, textvariable=self.cjcountStr,fg='#00009C').pack(side=LEFT, padx=2)


        if self.task_id in (47,50):
            self.dccountStr=StringVar(value='正在获取导出状态')
            f02b=Frame(f1)
            f02b.pack(fill=X,padx=2)
            Label(f02b, textvariable=self.dccountStr,fg='#00009C').pack(side=LEFT, padx=2)

        f03=Frame(f1)
        f03.pack(fill=X,padx=2)
        Label(f03, textvariable=self.startStr,fg='#97694F').pack(side=LEFT, padx=2)

        f04=Frame(f1)
        f04.pack(fill=X,padx=2)
        Label(f04, textvariable=self.endStr,fg='#97694F').pack(side=LEFT, padx=2)

        f05=Frame(f1)
        f05.pack(fill=X,padx=2)
        Label(f05, textvariable=self.statusStr,fg='red',width=30,anchor="w").pack(side=LEFT, padx=2)

        f06=Frame(f1)
        f06.pack(fill=X,padx=2)

        if self.isMulti==-1:
            Label(f06, text='《单进程》',font=label_font,fg='#871F78').pack(side=LEFT, padx=2)
        else:
            jc_index_dict={0:0,2:1,3:2,4:3,5:4,6:5,7:6,8:7}
            Label(f06, text='进程:',font=label_font).pack(side=LEFT)
            self.MutilSelect = ttk.Combobox(f06,state="readonly",width=3)
            self.MutilSelect['value']=['单进程','2','3','4','5','6','7','8']
            self.MutilSelect.current(jc_index_dict.get(self.isMulti))
            self.MutilSelect.bind("<<ComboboxSelected>>",lambda e :Thread(target=self.on_select_jcnum).start())
            self.MutilSelect.pack(side=LEFT)
            

        Label(f06, text='多定时:',font=label_font).pack(side=LEFT, padx=2)
        self.IptMutilTiming = Entry(f06,width=10)
        self.IptMutilTiming.pack(side=LEFT, padx=2, pady=2)
        if self.mutilTiming:
            self.IptMutilTiming.insert(0,self.mutilTiming)
        elif (self.timing!=-1) and (not self.mutilTiming):
            self.IptMutilTiming.insert(0,self.timing)

        self.btn_set_mutil_timing=Button(f06,text='保存',command=lambda:Thread(target=self.set_mutil_timing).start(),fg='#ffffff',bg='green')
        self.btn_set_mutil_timing.pack(side=LEFT,padx=2)

        if self.task_id==46:
            minp,maxp=800,6000
            
            if self.extraParam:
                extraParam=json.loads(self.extraParam)
                if extraParam.get('minPrice'):
                    minp=extraParam.get('minPrice')
                if extraParam.get('maxPrice'):
                    maxp=extraParam.get('maxPrice')
            f08=Frame(f1)
            f08.pack(fill=X,padx=2,pady=2)

            Label(f08, text='价格区间:',font=label_font).pack(side=LEFT, padx=2, pady=2)
            self.MinPriceIpt = Entry(f08,width=6)
            self.MinPriceIpt.pack(side=LEFT, padx=2, pady=2)
            self.MinPriceIpt.insert(0, minp)
            Label(f08,text='~').pack(side=LEFT, padx=2, pady=2)
            self.MaxPriceIpt = Entry(f08,width=6)
            self.MaxPriceIpt.pack(side=LEFT, padx=2, pady=2)
            self.MaxPriceIpt.insert(0, maxp)

            self.btn_set_price=Button(f08,text='保存',command=lambda:Thread(target=self.set_price).start(),fg='#ffffff',bg='green')
            self.btn_set_price.pack(side=LEFT,padx=2)

            

        f07=Frame(f1)
        f07.pack(fill=X,padx=2,pady=2)
        self.btn_start=Button(f07,text='开始运行',state=DISABLED,command=lambda:Thread(target=self.start_task).start(),fg='#ffffff',bg='green')
        self.btn_start.pack(side=LEFT,padx=2)

        self.btn_stop=Button(f07,text='停止运行',command=lambda:Thread(target=self.stop_task).start(),fg='#ffffff',bg='green')
        self.btn_stop.pack(side=LEFT,padx=2)

        self.btn_dc_log=Button(f07,text='导出日志',command=lambda:Thread(target=self.dc_log).start(),fg='#ffffff',bg='green')
        self.btn_dc_log.pack(side=LEFT,padx=2)
    
    def getcount(self):
        tb_name=self.table_name
        while True:
            try:
                if self.task_id in (46,47,48):
                    rs_search=self.ms.ExecQuery(f'select count(*) from {tb_name}')
                    self.countStr.set(f'菲律宾买家号共:{rs_search[0][0]} 个')
                elif self.task_id in (49,50):
                    rs_search=self.ms.ExecQuery(f'select count(*) from S1688Account')
                    self.countStr.set(f'阿里巴巴买家号共:{rs_search[0][0]} 个')

                self.mj_count=rs_search[0][0]
                if self.task_id==46:
                    sql_str='''
                            select count(*) from phlmurl where (lmurl is not null and  lmurl not in ('','原始链接下架')) 
                            and (lmcj_timestamp is null or ABS(DATEDIFF(SECOND, DATEADD(SECOND, lmcj_timestamp, '1970-01-01'), GETUTCDATE())) > 2592000)
                        '''
                    rs_cj=self.ms.ExecQuery(sql_str)

                    sql_str='''
                        select count(*) from phlmurl where (lmurl is not null and  lmurl not in ('','原始链接下架')) 
                        and (ABS(DATEDIFF(SECOND, DATEADD(SECOND, lmcj_timestamp, '1970-01-01'), GETUTCDATE())) < 2592000)
                        '''
                    rs_has_cj=self.ms.ExecQuery(sql_str)
                    self.cjcountStr.set(f'当前需采集:{rs_cj[0][0]} 个,已采集:{rs_has_cj[0][0]} 个')
                elif self.task_id==47:
    
                    sql_str=f'''select 
                                    count(case when is_cj=0 then 1 end),
                                    count(case when is_cj=1 then 1 end),
                                    count(case when Y_1688price is not null and is_cj=1 and yntitle is not null then 1 end),
                                    count(case when is_yn_dc=1 then 1 end)
                                    from shopeephadpro where shop_location='Mainland China'
                                    '''
                    rs_cj=self.ms.ExecQuery(sql_str)
                    not_cj,has_cj,can_dc,has_dc=rs_cj[0]
                    self.cjcountStr.set(f'当前需采集:{not_cj},已采集:{has_cj}')
                    self.dccountStr.set(f'可导出总数:{can_dc},已导出:{has_dc},未导出:{can_dc-has_dc}')
                elif self.task_id==48:
                    sql_str='''
                        select count(*) from phlmurl where (ysdpurl is not null and  ysdpurl not in ('','原始链接下架')) 
                        and (dpcj_timestamp is null or ABS(DATEDIFF(SECOND, DATEADD(SECOND, dpcj_timestamp, '1970-01-01'), GETUTCDATE())) > 2592000)
                        '''
                    rs_cj=self.ms.ExecQuery(sql_str)
                    sql_str='''
                        select count(*) from phlmurl where (ysdpurl is not null and  ysdpurl not in ('','原始链接下架')) 
                        and (ABS(DATEDIFF(SECOND, DATEADD(SECOND, dpcj_timestamp, '1970-01-01'), GETUTCDATE())) < 2592000)
                        '''
                    rs_has_cj=self.ms.ExecQuery(sql_str)
                    self.cjcountStr.set(f'当前需采集:{rs_cj[0][0]} 个,已采集:{rs_has_cj[0][0]} 个')
                elif self.task_id==49:
                    sql_str=f'''select 
                        count(case when is_cj=0 then 1 end),
                        count(case when is_cj=1 then 1 end) 
                        from S1688SearchUrl
                        '''
                    rs_cj=self.ms.ExecQuery(sql_str)
                    not_cj,has_cj=rs_cj[0]
                    self.cjcountStr.set(f'当前需采集:{not_cj},已采集:{has_cj}')
                
                elif self.task_id==50:

                    sql_str=f'''select 
                        count(case when is_cj=0 then 1 end),
                        count(case when is_cj=1 then 1 end),
                        count(case when pname not like '%定制%' and shujuzhuangtai='可广告测品' then 1 end),
                        count(case when pname not like '%定制%' and shujuzhuangtai='可广告测品' and is_fy_sku=1 then 1 end),
                        count(case when pname not like '%定制%' and shujuzhuangtai='可广告测品' and is_yn_dc=1  then 1 end),
                        count(case when pname not like '%定制%' and shujuzhuangtai='可广告测品' and is_yn_dc=0 and is_fy_sku=1 then 1 end)
                        from S1688Pro
                        '''
                    rs_cj=self.ms.ExecQuery(sql_str)
                    not_cj,has_cj,kcp,yfy,ydc,wdc=rs_cj[0]
                    self.cjcountStr.set(f'当前需采集:{not_cj},已采集:{has_cj}')
                    self.dccountStr.set(f'可广告测品:{kcp},测品已翻译:{yfy}\n测品已导出:{ydc},测品未导出:{wdc}')
  
                sqlstr2='select [state],[tcount],[LastRunTime],[LastEndTime],[LastHouTaiID] from task where [id]=?'
                rs2=self.ms.ExecQuery(sqlstr2,(self.task_id,))
                rwstatus,rwcount,start_time,end_time,last_hid=rs2[0]
                if rwstatus==0:
                    self.statusStr.set(f'任务未开启,最后运行买家号ID:{last_hid}')
                    self.btn_start.config(state=NORMAL)
                else:
                    self.statusStr.set(f'任务进行中,队列数剩余:{rwcount}')
                    self.btn_start.config(state=DISABLED)

                self.startStr.set(f'上次开始时间:{str(start_time)[:-7]}')
                self.endStr.set(f'上次结束时间:{str(end_time)[:-7]}')

            except Exception as e:
                pass
            time.sleep(20)
    
    def on_select_jcnum(self):

        if self.MutilSelect.current()==0:
            select_jc_num=0
        else:
            select_jc_num=int(self.MutilSelect.get())
        
        print(f'设置任务:《{self.task_name}》至进程数:{select_jc_num}...')

        aff=self.ms.ExecNoQuery('update task set isMulti=? where id=?',(select_jc_num,self.task_id))
        if aff>0:
            get_qukong_data()
            print(f'设置任务:《{self.task_name}》至进程数:{select_jc_num},设置成功')
        else:
            print(f'设置任务:《{self.task_name}》至进程数:{select_jc_num},设置失败')
            
    def on_select_timing(self):

        if self.TimingSelect.current()==0:
            timing_num=-1
        else:
            timing_num=int(self.TimingSelect.get())
        
        print(f'设置任务:《{self.task_name}》定时时间:{timing_num} 点运行...')

        aff=self.ms.ExecNoQuery('update task set timing=? where id=?',(timing_num,self.task_id))
        if aff>0:
            get_qukong_data()
            print(f'设置任务:《{self.task_name}》定时时间:{timing_num} 点运行,设置成功')
        else:
            print(f'设置任务:《{self.task_name}》定时时间:{timing_num} 点运行,设置失败')

    def set_mutil_timing(self):

        pattern = r"^([0-9]|1[0-9]|2[0-3])(\|([0-9]|1[0-9]|2[0-3]))*$"
        mutil_timging_str=self.IptMutilTiming.get().strip()
        
        if not mutil_timging_str:
            mutil_timging_str=None
            if self.timing:
                self.IptMutilTiming.insert(0,self.timing)

            
        else:
            if not re.match(pattern, mutil_timging_str):
                messagebox.showinfo('错误','请输入正确定时格式:2|4|23')
                return

        self.btn_set_mutil_timing.config(state=DISABLED)
        if mutil_timging_str:
            timing=int(mutil_timging_str.split('|')[0])
        else:
            timing=-1
        print(f'设置任务:《{self.task_name}》多个定时时间:{mutil_timging_str} ...')
        
        aff=self.ms.ExecNoQuery('update task set mutilTiming=?,timing=? where id=?',(mutil_timging_str,timing,self.task_id))
        
        if aff>0:
            get_qukong_data()
            print(f'设置任务:《{self.task_name}》多个定时时间:{mutil_timging_str} ,设置成功')
        else:
            print(f'设置任务:《{self.task_name}》多个定时时间:{mutil_timging_str} ,设置失败')
        
        self.btn_set_mutil_timing.config(state=NORMAL)

    def set_price(self):
        maxp=int(self.MaxPriceIpt.get().strip())
        minp=int(self.MinPriceIpt.get().strip())

        
        if minp>maxp:
            messagebox.showerror('提示','最低价格不得高于最高价格')
            return
        self.btn_set_price.config(state=DISABLED)
        print(f'设置任务:《{self.task_name}》最低价格:{minp},最高价格:{maxp}')

        sqlstr=f'''
                UPDATE task
                SET extraParam = 
                    CASE 
                        WHEN extraParam IS NULL THEN '{{"minPrice":{minp},"maxPrice":{maxp}}}'
                        ELSE JSON_MODIFY(
                            JSON_MODIFY(extraParam, '$.minPrice', {minp}),
                            '$.maxPrice', {maxp}
                        )
                    END
                WHERE id = ?
                '''
        aff=self.ms.ExecNoQuery(sqlstr,(self.task_id,))
        if aff>0:
            get_qukong_data()
            print(f'任务:《{self.task_name}》最低价格:{minp},最高价格:{maxp},设置成功')
        else:
            print(f'任务:《{self.task_name}》最低价格:{minp},最高价格:{maxp},设置失败')

        self.btn_set_price.config(state=NORMAL)

    def start_task(self):

        if not messagebox.askyesno('提示',f'确定开启{self.task_name}任务?'):
            return
        self.btn_start.config(state=DISABLED)
        
        aff1=self.ms.ExecNoQuery('update [task] set state=1,tcount=?,LastHouTaiID=null where [id]=?',(self.mj_count,self.task_id))
        if aff1:
            print(f'开启任务{self.task_name}任务成功')
        else:
            print(f'开启{self.task_name}任务失败')
            messagebox.showerror('提示',f'开启{self.task_name}任务失败')
    


    def stop_task(self):

        self.btn_stop.config(state=DISABLED)

        aff=ms.ExecNoQuery('update task set state=-1 where id=? and state!=0',(self.task_id,))
        if aff>0:
            print(f'成功关闭任务《{self.task_name}》')
            messagebox.showinfo('提示',f'成功关闭任务《{self.task_name}》')
        else:
            print(f'关闭任务《{self.task_name}》失败')
            messagebox.showinfo('提示',f'关闭任务《{self.task_name}》失败')

        self.btn_stop.config(state=NORMAL)

    def dc_log(self):

        self.btn_dc_log.config(state=DISABLED)
        rs=self.ms.ExecQuery('select logPath from task where id=?',(self.task_id,))
        if not rs[0][0]:
            print(f'当前没有 {self.task_name} 的运行日志')
        else:
            logPath=rs[0][0]
            url=logPath.replace('D:/Web/Gtupdate',f'http://{UPDATE_URL}')
            print(url)
            while True:
                try:
                    res=requests.get(url)
                    bdpath=logPath.replace('D:/Web/Gtupdate/GTLOG/','')
                    with open(bdpath,'wb') as f:
                        f.write(res.content)
                    print(f'成功导出{self.task_name} 运行日志:《{bdpath}》')
                    messagebox.showinfo('提示',f'成功导出{self.task_name} 运行日志:《{bdpath}》')
                    break 
               
                except Exception as e:
                    print(e)
                    time.sleep(1)
    
        self.btn_dc_log.config(state=NORMAL)

class S1688AddUrlFrame(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.createWidgets()


    def createWidgets(self):
        f0=Frame(self)
        f0.pack(fill=X)
        f00=Frame(f0)
        f00.pack(fill=X,padx=2)
        Label(f00, text=f'《导入阿里巴巴集合页链接》',fg='#6B238E',font=("微软雅黑", 12),anchor="w").pack(side=LEFT, padx=2)

        f02=Frame(f0)
        f02.pack(fill=X,pady=2)
        label_font = tkfont.Font(family="微软雅黑", size=10, weight="bold")
        Label(f02, text='输入单个或者多个链接(一行一个链接):',font=label_font).pack(side=LEFT, padx=2)

        f03=Frame(f0)
        f03.pack(fill=X)
        self.KWIpt = Text(f03,height=6,width=30)
        self.KWIpt.pack(side=LEFT,pady=2)

        f06=Frame(f0)
        f06.pack(fill=X)
        Label(f06, text='商家编码:',font=label_font).pack(side=LEFT, padx=2)
        self.sjbmIpt = Entry(f06)
        self.sjbmIpt.pack(side=LEFT,pady=2)

        f04=Frame(f0)
        f04.pack(fill=X)
        self.btn_add_url=Button(f04,text=f'新增待采集链接',command=lambda:Thread(target=self.add_url).start(),fg='#ffffff',bg='green')
        self.btn_add_url.pack(side=LEFT,padx=2,pady=2)

        f05=Frame(f0)
        f05.pack(fill=X)

        Label(f05, text='大于',font=label_font).pack(side=LEFT, padx=2)
        self.IptResetDay= Entry(f05,width=3)
        self.IptResetDay.pack(side=LEFT, padx=2, pady=2)
        self.IptResetDay.insert(0,'30')
        Label(f05, text='天',font=label_font).pack(side=LEFT, padx=2)
        
        self.btn_reset=Button(f05,text=f'重置链接采集状态',command=lambda:Thread(target=self.reset_url).start(),fg='#ffffff',bg='green')
        self.btn_reset.pack(side=LEFT,padx=2,pady=2)


    
    def add_url(self):

        kwstr=self.KWIpt.get("1.0", "end").strip()
        sjbm= self.sjbmIpt.get().strip()

        if not kwstr or not sjbm:
            messagebox.showerror('提示','请先输入内容')
            return
        self.btn_add_url.config(state=DISABLED)

        url_list=kwstr.split('\n')
        if not messagebox.askyesno('提示',f'是否将 {len(url_list)} 个阿里巴巴链接导入'):
            return
        
        print(f'共 {len(url_list)} 个阿里巴巴链接,开始导入...')
        j=1
        suc=0
        ign=0
        fail=0
        cur_time=datetime.now()
        
        for kw in url_list:
            kw=kw.strip()
            rs=self.ms.ExecQuery('select count(*) from S1688SearchUrl where url=?',(kw,))
            if rs[0][0]>0:
                ign+=1
                j+=1
                continue

            pdata={

                'url':kw,
                'sjbm':sjbm,
                'update_time':cur_time,
                'upload_time':cur_time
            }

            zds=list(pdata.keys())
            params=list(pdata.values())
            zdstr=','.join(zds)
            wstr=','.join(['?' for _ in params])
            aff=self.ms.ExecNoQuery(f'insert into S1688SearchUrl({zdstr}) values({wstr})',params)
            print(f'商家编码:《{sjbm}》第 {j} 个链接:《{kw}》,存入表《S1688SearchUrl》状态:{aff}')
            if aff:
                suc+=aff
            else:
                fail+=1
            j+=1

        print(f'本次共{len(url_list)}个链接,其中导入成功:{suc},失败:{fail},已存在忽略:{ign}')
        messagebox.showinfo('提示',f'本次共{len(url_list)}个链接,其中导入成功:{suc},失败:{fail},已存在忽略:{ign}')

        self.btn_add_url.config(state=NORMAL)

    def reset_url(self):
        
        reset_day_str=self.IptResetDay.get().strip()

        if not reset_day_str:
            messagebox.showerror('提示','请输入指定天数')
            return
        rest_day=int(reset_day_str)
        if not messagebox.askyesno('提示',f'确定重置大于 {rest_day} 天的所有链接采集状态?'):
            return
        timestamp=rest_day*86400
        self.btn_reset.config(state=DISABLED)
        sqlstr=f'''update S1688SearchUrl set is_cj=0 where is_cj=1 
                    and ABS(DATEDIFF(SECOND, DATEADD(SECOND, last_cj_time, '1970-01-01'), GETUTCDATE())) > {timestamp} '''
        aff=self.ms.ExecNoQuery(sqlstr)
        print(f'成功将 {aff} 个阿里巴巴搜索链接状态采集状态重置为未采集')
        messagebox.showinfo('提示',f'成功将 {aff} 个阿里巴巴搜索链接状态采集状态重置为未采集')

        self.btn_reset.config(state=NORMAL)



class PHMianBanFrame(Frame):
    def __init__(self,master,mbName):
        Frame.__init__(self,master)
        self.mbName=mbName
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)

        self.createWidgets()
        Thread(target=self.getcount).start()

    def createWidgets(self):

        if not get_config('QKTask'):
            print('正在加载群控面板数据...')
            get_qukong_data()
        
        rw_datas=get_config('QKTask')[self.mbName]
        rw_datas.sort(key=lambda item: (item['timing'] == -1, item['timing']))
        row=1;col=1
        row_count=3
        for j in range(len(rw_datas)+1):
            
            f0= Frame(self)
            f0.grid(row=row, column=col, padx=2,pady=2, sticky="NW")
            if j<3:
                rw=rw_datas[j]
                PHTaskFrame(f0,rw).pack(fill=X)
            elif j==3:
                S1688AddUrlFrame(f0).pack(fill=X)
            else:
                rw=rw_datas[j-1]
                PHTaskFrame(f0,rw).pack(fill=X)
           
            col+=1
            if col>row_count:
                col=col%row_count
                row+=1

    
    def getcount(self):
        while True:
            try:
                get_qukong_data()
            except Exception as e:
                pass
            time.sleep(1200)



class DinZhiFrame(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.dpCount=StringVar()
        self.dpCount.set('正在获取POD关键词总数...')
        self.rowCount=IntVar()
        self.createWidgets()
        Thread(target=self.getcount).start()

    def createWidgets(self):


        f0=Frame(self)
        f0.pack(fill=X,padx=2,pady=2)
        Label(f0, text='POD关键词导入', fg="white", bg="#007FFF",font=("微软雅黑", 13)).pack(fill=X,padx=5)
        Label(f0, textvariable=self.dpCount,fg='red',anchor='w').pack(fill=X,padx=2, pady=2)


        f01=Frame(f0)
        f01.pack(fill=X,side=LEFT,padx=6,pady=2)

        Label(f01, text='关键词文件:').pack(side=LEFT, padx=2, pady=2)
        self.DaoRuIpt = Entry(f01)
        self.DaoRuIpt.pack(side=LEFT, padx=2, pady=2)
        Button(f01,text='选择文件',fg='#ffffff',bg='green',command=self.choosefile).pack(side=LEFT,padx=2, pady=2)

        Label(f01, text='输入源词:').pack(side=LEFT, padx=2, pady=2)
        self.YKWIpt = Entry(f01)
        self.YKWIpt.pack(side=LEFT, padx=2, pady=2)

        self.drbtn=Button(f01,text='上传关键词',command=lambda:Thread(target=self.start_dr).start(),fg='#ffffff',bg='green',width=20)
        self.drbtn.pack(side=LEFT, padx=2, pady=2)

    def choosefile(self):
        select_path=filedialog.askopenfilename()
        if select_path.endswith('.txt'):
            self.DaoRuIpt.delete(0, END)
            self.DaoRuIpt.insert(0,select_path)
            self.fpath=select_path
        else:
            messagebox.showerror('错误提示','请选择txt文件')
    
    def getcount(self):
        while True:
            try:
                rs=self.ms.ExecQuery('''SELECT COUNT(*) from AmazonKW''')
                rs1=self.ms.ExecQuery('''SELECT COUNT(*) from AmazonKW where state=0''')    
                self.dpCount.set(f'共 {rs[0][0]} 个关键词,已采集:{rs[0][0]-rs1[0][0]}个,未采集:{rs1[0][0]}')
                time.sleep(10)
            except Exception as e:
                print(e)

    def start_dr(self):
        txt_path=self.DaoRuIpt.get().strip()
        ykw=self.YKWIpt.get().strip()
        if not txt_path or not ykw:
            messagebox.showinfo('提示','请先导入关键词文件')
            return
        def up_kw(cur_kw):
            aff=0
            rs= self.ms.ExecQuery('select count(*) from AmazonKW where kw=?',(cur_kw,))
            if rs[0][0]==0:
                aff=self.ms.ExecNoQuery('insert into AmazonKW(kw,source_word) values(?,?)',(cur_kw,ykw))
            return cur_kw,aff
        

        self.drbtn.config(state=DISABLED)
        suc=0
        fail=0
        kws=[]
        with open(txt_path,'r',encoding='utf-8') as f:
            cot=f.read()
        
        kws=[ line.strip() for line in cot.split('\n')]

        task_count=len(kws)
        print(f'共有 {task_count} 个关键词待上传...')
        with thddd.ThreadPoolExecutor(max_workers=10) as t0:
            tasks=[t0.submit(up_kw,cur_kw) for cur_kw in kws]

            for t in tasks:
                res_kw,res_aff=t.result()
                if res_aff:
                    suc+=res_aff
                else:
                    fail+=1
                task_count-=1
                print(f'关键词:《{res_kw}》,上传完毕,状态:{res_aff},剩余任务队列:{task_count}/{len(kws)}')

        print(f'上传关键词完毕,成功:{suc},失败:{fail}')
        messagebox.showinfo('提示',f'上传关键词完毕,成功:{suc},失败:{fail}')
        self.drbtn.config(state=NORMAL)

# import tkinter
# list_win=tkinter.Tk()
# list_win.wm_geometry("800x650")
# list_win.title('amazon')
# AmazonFra(list_win).pack(fill=X,padx=3,pady=3)
# list_win.mainloop()